package dao

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
	"time"
)

func (d *Dao) QueryPmsProductFullInfo(ctx context.Context, ids []int64) ([]model.ViewProductFull, error) {
	tb := model.ViewProductFull{}
	result := []model.ViewProductFull{}

	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("id IN ?", ids).Find(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) UpdateProductAndCrowdFunding(ctx context.Context, ProductId, ProductSkuId, CrowdFundingId, CrowdFundingThaliId, OrderId, MemberId int64) error {
	if err := d.db.Transaction(func(tx *gorm.DB) error {

		// 先查找是否存在数据了 如果存在就不添加
		logTb := model.SmsCrowdFundingLog{}
		if err := d.db.WithContext(ctx).Table(logTb.TableName()).Where("member_id = ? AND order_id = ?", MemberId, OrderId).First(&logTb).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				goto next
			} else {
				return err
			}
		}

		if logTb.ID > 0 {
			return errors.New("已经存在此记录，跳过")
		}
	next:
		tb := model.ViewProductCrowdFundingDetail{}
		result := model.ViewProductCrowdFundingDetail{}

		if err := tx.WithContext(ctx).Table(tb.TableName()).Where("crowd_funding_id = ? AND crowd_funding_thali_id = ? AND product_sku_id = ? AND product_id = ?", CrowdFundingId, CrowdFundingThaliId, ProductSkuId, ProductId).First(&result).Error; err != nil {
			return err
		}

		global.Log.Info("查询完毕", zap.Any("data", result))

		// 根据订单找到对应的用户并修改数据
		insertModel := model.SmsCrowdFundingLog{
			OrderId:             OrderId,
			MemberId:            MemberId,
			CrowdFundingId:      CrowdFundingId,
			ProductId:           ProductId,
			ProductSkuId:        ProductSkuId,
			CrowdFundingThaliId: CrowdFundingThaliId,
			ThaliPrice:          result.CftThaliPrice,
			Number:              1,
			TotalPrice:          result.CftThaliPrice,
			Status:              1,
			MemberStatus:        1,
			CreateTime:          time.Now(),
		}
		if err := tx.WithContext(ctx).Table(insertModel.TableName()).Create(&insertModel).Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	}); err != nil {
		return err
	}
	return nil
}
